﻿$(document).ready(function () {

    var get_element = function (value, options) {
        var element = $($("<input type='text' class='FormElement ui-widget-content ui-corner-all' />")[0]);
        element.autocomplete({ source: '/Customer/SearchCustomers', max: 25, highlight: true, mustMatch: true, minChars: 3, autoFill: true});
        return element;
    };
    var get_value = function (element, operation, value) {
        if (operation === 'get') {
            return $(element).val();
        } if (operation === 'set') {
            $(element).val(value);
        }
    };

    var check_selected_row = function(grid){        
        var id = grid.getGridParam('selrow');
        if(!id){
            $($("<div title='Warning'><p>Please select a row.</p></div>")[0]).dialog({height: 125, modal: true});
        }
        return id;
    };

    var show_add_license_entitlement_form = function(){
        var id = $('#CustomerEntitlementId').val();
        if(!id){
            return;
        }
        $.get('/Entitlement/GetCustomerName', {id: id}, function(data) {
        $('#AddLicenseEntitlementForm').clearForm();
        $('#AddLicenseEntitlementForm input[name=Customer]').val(data);
        $('#AddLicenseEntitlementFormContainer').dialog({ title: 'Add a license entitlement', width: 500, modal: true, position: ['center', 'center'] });            
        });
    };

    var delete_license_entitlement = function(id){
        var licenseEntitlementId = $('#entitlementsList').getCell(id, 'Id');
        var customerEntitlementId = $('#CustomerEntitlementId').val();

        $.post('/Entitlement/DeleteLicenseEntitlement', {customerEntitlementId: customerEntitlementId, licenseEntitlementId: licenseEntitlementId}, function(result){
            if(result && result[0]){
                $('#entitlementsList').trigger('reloadGrid');
                $('#list').trigger('reloadGrid');
            }            
        });
    };

    var download_license = function(){
        var id = check_selected_row($('#list'));
        if(!id){
            return;
        }

        var customerEntitlementId = $('#list').getCell(id, 'Id');
        window.location = '/Entitlement/GetCustomerEntitlementFile?customerEntitlementId=' + customerEntitlementId;
    };

    var view_customer_key = function(){
            var id = check_selected_row($('#list'));
            if(!id){
                return;
            }

            var customerEntitlementId = $('#list').getCell(id, 'Id');
            $.post('/Entitlement/GetCustomerKey', {customerEntitlementId: customerEntitlementId}, function(result){
            if(result && result[0]){
                $($('<div><p style="width:200px; word-wrap:break-word">' + result[2] + '</p></div>')[0]).dialog();
            }            
        });
    };

    var show_license_entitlements = function(){
        $('#CustomerEntitlementId').val('');   
        $("#entitlementsList").jqGrid('GridUnload');             
        var id = check_selected_row($('#list'));
        if(!id){
            return;
        }
        var guid = $('#list').getCell(id, 'Id');

        $('#CustomerEntitlementId').val(guid);        

        $("#entitlementsList").jqGrid({
            height: 300,
            width: 1050,
            url: '/Entitlement/GetLicenseEntitlementsDataForCustomer',
            datatype: 'json',
            postData: {customerEntitlementId: guid},            
            mtype: 'POST',
            colNames: ['Id', 'Product', 'License', 'Feature'],
            colModel: [
              { name: 'Id', index: 'Id', width: 275, sortable: false },
              { name: 'Product', index: 'Product', width: 250, sortable: false },
              { name: 'License', index: 'License', width: 250, sortable: false },
              { name: 'Feature', index: 'Feature', width: 250, sortable: false },              
              ],
            pager: jQuery('#entitlementsPager'),
            rowNum: 10,
            rowList: [10, 50],
            viewrecords: true,
            imgpath: '/Content/images',
            caption: 'License Entitlements',
        }).navGrid('#entitlementsPager', { edit: false, add: true, del: true, search: false, addfunc: function() {show_add_license_entitlement_form();}, delfunc: delete_license_entitlement }
                           , {}
                           , { addCaption: 'Add a license entitlement'}
                           , { url: '/Entitlement/DeleteLicenseEntitlement'});
        
        $('#ShowLicenseEntitlementsContainer').dialog({width: 1100, modal: true});
    };

    $("#list").jqGrid({
        width: 1200,
        url: '/Entitlement/GetEntitlementsData/',
        datatype: 'json',
        mtype: 'POST',
        colNames: ['Id', 'Customer', 'Products'],
        colModel: [
          { name: 'Id', index: 'Id', width: 275, sortable: false },
          { name: 'Customer', index: 'Customer', width: 325, sortable: false, editable: true, edittype: 'custom', editrules: { required: true }, editoptions: { custom_element: get_element, custom_value: get_value}  },
          { name: 'Products', index: 'Products', width: 600, sortable: false }
          ],
        pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [10, 50],
        sortname: 'name',
        sortorder: "asc",
        viewrecords: true,
        imgpath: '/Content/images',
        caption: 'Entitlements',
    }).navGrid('#pager', { edit: false, add: true, del: false, search: false}
                       , {}
                       , { addCaption: 'Add an entitlement', url: '/Entitlement/New/', closeAfterAdd: true, reloadAfterSubmit: true, afterSubmit: jqgridHelpers.after_submit })
      .jqGrid('navButtonAdd',"#pager",{caption: "", buttonicon:"ui-icon-info", onClickButton: show_license_entitlements, title:"View license entitlements", cursor: "pointer"})
      .jqGrid('navButtonAdd',"#pager",{caption: "", buttonicon:"ui-icon-download", onClickButton: download_license, title:"Download customer entitlement", cursor: "pointer"})
      .jqGrid('navButtonAdd',"#pager",{caption: "", buttonicon:"ui-icon-key", onClickButton: view_customer_key, title:"View customer key", cursor: "pointer"});

    $('#AddLicenseEntitlementForm input[name=Product]').autocomplete({ source: '/Product/SearchProducts', highlight: true, multiple: false, mustMatch: true, minChars: 3, autoFill: true });
    $('#AddLicenseEntitlementForm input[name=License]').autocomplete({ source: '/License/SearchLicenses', highlight: true, multiple: false, mustMatch: true, minChars: 3, autoFill: true });
    $('#AddLicenseEntitlementForm input[name=Node]').autocomplete({ source: '/Node/SearchNodes', highlight: true, multiple: false, mustMatch: true, minChars: 3, autoFill: true });
    $('#AddLicenseEntitlementForm input[name=ValidFrom]').datepicker({dateFormat: 'dd/MM/yy'});
    $('#AddLicenseEntitlementForm input[name=ValidTo]').datepicker({dateFormat: 'dd/MM/yy'});


    $('#AddLicenseEntitlementForm a[name=Submit]').click(function () { $('#AddLicenseEntitlementForm').submit(); });
    $('#AddLicenseEntitlementForm a[name=Cancel]').click(function () { $("#AddLicenseEntitlementFormContainer").dialog("close"); });
    $('#AddLicenseEntitlementForm').validate();
    $('#AddLicenseEntitlementForm').ajaxForm({
        success: function (data) {
            if (data && data[0]) {
                $("#AddLicenseEntitlementFormContainer").dialog("close");
                $('#entitlementsList').trigger('reloadGrid');
                $('#list').trigger('reloadGrid');
            }
        }
    });
}); 